using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace ZSW.Framework.EditorTools
{
    public class ResetPivotCenter
    {
        [MenuItem("Tools/Transform/Reset Pivot Center")]
        [MenuItem("GameObject/Tools/Reset Pivot Center")]
        public static void Invoke()
        {
            resetPivot();
        }

        // 设置对象的轴心为渲染边界中心
        private static Transform resetPivot()
        {
            GameObject target = Selection.activeGameObject;
            string orignal_name = target.name;
            // target.name = "model";

            if (target == null)
            {
                Debug.Log("没有选中需要重置轴心的物体!!!");
                return null;
            }

            MeshRenderer[] meshRenderers = target.GetComponentsInChildren<MeshRenderer>(true);
            if (meshRenderers.Length == 0)
            {
                Debug.Log("选中的物体不是有效模型物体!!!");
                return null;
            }

            Bounds centerBounds = meshRenderers[0].bounds;
            for (int i = 1; i < meshRenderers.Length; i++)
            {
                centerBounds.Encapsulate(meshRenderers[i].bounds);
            }

            Transform targetParent = new GameObject(orignal_name).transform;

            Transform originalParent = target.transform.parent;
            if (originalParent != null)
            {
                Undo.SetTransformParent(targetParent, originalParent, "Reset Pivot");
            }

            targetParent.position = centerBounds.center;

            Undo.SetTransformParent(target.transform, targetParent, "Reset Pivot");

            Selection.activeGameObject = targetParent.gameObject;
            Debug.Log($"重置{orignal_name}的轴心完成!");
            return targetParent;
        }
    }
}